package pl.multimedialne.carculator.gui;

import pl.multimedialne.carculator.R;
import pl.multimedialne.carculator.sensors.Accelerometer;
import pl.multimedialne.carculator.sensors.GPS;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class StatsFragment extends Fragment {
	
	public float display;
	public boolean isSpeedDisplayed = true;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_stats, container,
				false);

		final Activity a = getActivity();
		Thread t = new Thread() {
			@Override
			public void run() {
				final View v = getView();
				try {
					while (!isInterrupted()) {
						Thread.sleep(50);
						a.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								float speed = GPS.getInstance().isEnabled() ? (GPS
										.getInstance().getSpeed() + Accelerometer
										.getInstance().getSpeed()) / 2
										: Accelerometer.getInstance()
												.getSpeed();
								float acceleration = Accelerometer.getInstance()
										.getAcceleration();
								if (isSpeedDisplayed) display = speed;
								else display = acceleration;
								((TextView) v.findViewById(R.id.textView9))
										.setText(String.format("%.1f", display));
								((TextView) v.findViewById(R.id.textView2))
										.setText(String.format("%.1f", speed));
								((TextView) v.findViewById(R.id.textView6))
										.setText(String.format("%.1f", acceleration));
							}
						});
					}
				} catch (InterruptedException e) {
				}
			}
		};
		t.start();
		return rootView;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		Button buttonSpeed = (Button) getView().findViewById(R.id.textView1);
		Button buttonAcceleration = (Button) getView().findViewById(R.id.textView5);
		
		buttonSpeed.setOnClickListener(new View.OnClickListener() { 
		    public void onClick(View view) { 
		    	isSpeedDisplayed = true;
		    	((TextView) getView().findViewById(R.id.textView10))
				.setText("km/h");
		       }
		    });
		buttonAcceleration.setOnClickListener(new View.OnClickListener() { 
		    public void onClick(View view) { 
		    	isSpeedDisplayed = false;
		    	((TextView) getView().findViewById(R.id.textView10))
				.setText("N/kg");
		       }
		    });
	}
}
